package ilincar.systemcore.service;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.provider.Settings;
import android.text.TextUtils;

import ilincar.systemcore.tool.ILog;
import ilincar.systemcore.util.CommonUtils;

public class BootReceiver extends BroadcastReceiver {

    private final String TAG = "BootReceiver";

    private final String BOOT_COMPLETED = Intent.ACTION_BOOT_COMPLETED;

    public BootReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        String action = intent.getAction();
        //启动CameraService
        if(action.equals(BOOT_COMPLETED)){
            ILog.d(TAG, "接收到系统启动广播，启动SystemCore");
            Intent i = new Intent();
            i.setClass(context, CoreService.class);
            context.startService(i);
            i = null;
            new WifiTask(context).execute();
        }
    }

    private boolean isWifiEnable = false;

    /**
     * 打开WIFI，并记录打开前的状态
     * @param ctx
     */
    private void openWifi(Context ctx) {
        isWifiEnable = CommonUtils.openWifi(ctx);
    }

    private void otherDeal(Context ctx) {
        openWifi(ctx);
    }

    /***
     * 为了能获取到WIFI的MAC地址而用的
     */
    private class WifiTask extends AsyncTask<Void, Void, Void> {
        Context mCtx;
        public WifiTask(Context ctx) {
            mCtx = ctx;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            String mac = Settings.System.getString(mCtx.getContentResolver(), "mac_addr");
            if (!TextUtils.isEmpty(mac))
                return null;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            otherDeal(mCtx);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mac = ilincar.utils.IlincarUtils.getIntMacByShell();
            if (mac != null && !"".equals(mac)) {
                Settings.System.putString(mCtx.getContentResolver(), "mac_addr", mac);
            }
            CommonUtils.closeWifi(mCtx, isWifiEnable);
            return null;
        }
    }
}
